<?php
use think\Request;
use think\Validate;
use think\Db;

/**
 * 检查表单令牌
 * @param        string        $token        表单令牌
 * @return      bool
 * */
function checkToken($token)
{
	$data = ['__token__' => $token];
	$rule = ['__token__' => 'token'];
	$msg = ['__token__' => '请不要刷新该页面！'];
	//引入验证类
	$validate = Validate::make($rule, $msg);
	if ($validate->check($data)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 按综合方式输出通信数据（后台异步返回信息专用）
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $url           参考 url() 方法；链接：https://www.kancloud.cn/manual/thinkphp5/118041
 * @param        int            $timer         跳转时间
 * @return      string
 */
function adminReturn($result, $msg = '', $url = '', $timer = 1000)
{
	if ($result == 1) {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'url' => $url,
			'timer' => intval($timer)
		);
	} else {
		$request = Request::instance();
		$token = $request->token();

		$message = array(
			'result' => $result,
			'msg' => $msg,
			'url' => $url,
			'token' => $token,
			'timer' => intval($timer)
		);
	}

	echo json_encode($message);
	exit;
}

/**
 * REDIRECT_URL处理
 * */
function doRedirectUrl()
{
	$redirect_url = $_SERVER['REDIRECT_URL'];
	if ($redirect_url == '/admin') {
		return '/admin/index/index.html';
	} else {
		$redirect_url_arr = explode('/', $redirect_url);

		return '/' . $redirect_url_arr[1] . '/' . $redirect_url_arr[2] . '/' . $redirect_url_arr[3];
	}
}

/**
 * 获取顶级菜单ID
 * @param        int        $id        子菜单id
 * */
function getTopId($id)
{
	$info = Db::name('menu')->field('id,pid,level')->where(['id' => $id])->find();
	if ($info['level'] > 1) {
		return getTopId($info['pid']);
	} else {
		return $info['id'];
	}
}

/**
 * 点击顶部菜单获取匹配的左侧菜单
 * @param        string        $id        顶部菜单id
 * @return      bool
 * */
function showLeftMenu($id)
{
	$request_uri = $_SERVER['REDIRECT_URL'] == '/admin' ? '/admin/index/index' : doRedirectUrl();

	$info = Db::name('menu')->field('id,pid')->where(['url' => str_replace('.html', '', $request_uri)])->find();
	$top_id = getTopId($info['id']);

	if ($top_id == $id) {
		return true;
	}

	return false;
}

/**
 * 菜单高亮
 * @param        int        $id           id
 * @param        int        $level        1：顶部菜单，2：左侧分组菜单，3：左侧分组子菜单
 * @return      bool
 * */
function leftMenuActive($id, $level)
{
	$request_uri = $_SERVER['REDIRECT_URL'] == '/admin' ? '/admin/index/index' : doRedirectUrl();

	if ($level == 2) {
		$count = Db::name('menu')->where(['pid' => $id, 'is_show' => 1, 'level' => $level])->count();
		if ($count > 0) {
			//有显示的子菜单
			$info = Db::name('menu')->field('pid')->where(['url' => str_replace('.html', '', $request_uri), 'pid' => ['gt', 0]])->find();
			if ($info['pid'] == $id) {
				return true;
			} else {
				return false;
			}
		} else {
			//无显示的子菜单
			$info = Db::name('menu')->field('id,pid')->where(['url' => str_replace('.html', '', $request_uri), 'pid' => ['gt', 0]])->find();
			if ($info['id'] == $id) {
				return true;
			} else {
				if ($info['pid'] == $id) {
					return true;
				}
			}
		}
	} else if ($level == 3) {
		$info = Db::name('menu')->field('id')->where(['url' => str_replace('.html', '', $request_uri), 'pid' => ['gt', 0], 'level' => $level])->find();
		if ($info['id'] == $id) {
			return true;
		}
	}
}

/**
 * 更新URL（顶部菜单，分组菜单）
 * 调用时机：当对level=3的菜单操作完成后，执行该方法
 * */
function renewTopAndGroupUrl()
{
	//顶部菜单
	$top_list = Db::name('menu')->field('id,url')->where(['pid' => 0, 'level' => 1, 'status' => 1, 'is_show' => 1])->order('sort asc')->select();
	if ($top_list) {
		foreach ($top_list as &$v) {
			//分组菜单
			$group_list = Db::name('menu')->field('id,pid,url')->where(['pid' => $v['id'], 'level' => 2, 'status' => 1, 'is_show' => 1])->order('sort asc')->select();
			if ($group_list) {
				foreach ($group_list as $key => &$val) {
					//第一个子菜单
					$son_first_info = Db::name('menu')->field('id,pid,url')->where(['pid' => $val['id'], 'level' => 3, 'status' => 1, 'is_show' => 1])->order('sort asc')->find();

					if ($son_first_info) {
						//更新分组菜单URL
						Db::name('menu')->where(['id' => $val['id']])->update(['url' => $son_first_info['url'], 'update_time' => time()]);
						//更新顶部菜单URL
						if ($key == 0) Db::name('menu')->where(['id' => $v['id']])->update(['url' => $son_first_info['url'], 'update_time' => time()]);
					} else {
						//更新顶部菜单URL
						if ($key == 0) Db::name('menu')->where(['id' => $v['id']])->update(['url' => $val['url'], 'update_time' => time()]);
					}
				}
			}
		}
	}
}

/**
 * 获取上级菜单名称
 * @param        int        $pid        上级菜单id
 * @return      string
 **/
function getParentMenuName($pid)
{
	if ($pid > 0) {
		$info = model('menu')->get($pid);

		return $info ? $info->name : '无';
	} else {
		return '无';
	}
}

/**
 * 获取上级菜单ID
 * @param        int        $pid        上级菜单id
 * @return      int
 **/
function getParentMenuId($pid)
{
	if ($pid > 0) {
		$info = model('menu')->get($pid);

		return $info ? $info->id : 0;
	} else {
		return 0;
	}
}

/**
 * 获取访问授权未选中的父级菜单ID
 * @param        int          $id           菜单id
 * @param        array        $rules        待加入未选中父级菜单ID数组
 * */
function getNoCheckParentId($id, &$rules)
{
	$pid = Db::name('menu')->where(['id' => $id])->column('pid');
	if ($pid[0] > 0) {
		$parent_id = getParentMenuId($pid[0]);
		if ($parent_id > 0 && !in_array($parent_id, $rules)) {
			$rules[] = $parent_id;

			return getNoCheckParentId($parent_id, $rules);
		} else {
			return $rules;
		}
	}
}

/**
 * 判断访问授权复选框是否选中
 * @param        int        $group_id        全选分组id
 * @param        int        $menu_id         菜单ID
 * */
function authChecked($group_id, $menu_id)
{
	$rules = Db::name('auth_group')->where(['id' => $group_id])->column('show_rules');
	$rules = $rules[0];

	if (in_array($menu_id, explode(',', $rules))) {
		return 'checked';
	} else {
		return '';
	}
}

/**
 * 单图上传
 * @param        file        $file        图片文件
 * @return json
 * */
function adminUploadImg($file)
{
	$file_path = 'uploads/picture/';

	$save_picture_path = $file_path . date("Y-m-d");
	if (!is_dir($save_picture_path)) mkdir($save_picture_path, 0777, true);

	if ($file['name'] == '') {
		return apiReturn(2, '请上传图片');
	} else {
		if (is_uploaded_file($file['tmp_name'])) {
			$str = getExtension($file['name']);
			$avatar_path = $file_path . date("Y-m-d") . "/" . time() . rand(1000, 9999) . '.' . $str;

			if (copy($file['tmp_name'], $avatar_path)) {
				$cover['path'] = "/" . $avatar_path;
				$cover['create_time'] = time();
				$result_avatar_id = Db::name('picture')->insertGetId($cover);

				if ($result_avatar_id) {
					unlink($file['tmp_name']);
					$data = [
						'id' => $result_avatar_id,
						'img' => getPicture($result_avatar_id)
					];

					return apiReturn(1, '图片上传成功', $data);
				} else {
					return apiReturn(2, '图片上传失败');
				}
			} else {
				return apiReturn(2, '图片上传失败');
			}
		}
	}
}

function adminUploadFile($files)
{
	$file_path = 'uploads/file/';

	$save_picture_path = $file_path . date("Y-m-d");
	if (!is_dir($save_picture_path)) mkdir($save_picture_path, 0777, true);

	$file = $files['file_obj'];

	if ($file['name'] == '') {
		return apiReturn(2, '请上传文件');
	} else {
		if (is_uploaded_file($file['tmp_name'])) {
			$str = getExtension($file['name']);
			$avatar_path = $file_path . date("Y-m-d") . "/" . time() . rand(1000, 9999) . '.' . $str;

			if (copy($file['tmp_name'], $avatar_path)) {
				unlink($file['tmp_name']);

				return apiReturn(1, '文件上传成功', ['upload_file_name' => $file['name'], 'upload_file_path' => $avatar_path]);
			} else {
				return apiReturn(2, '文件上传失败');
			}
		} else {
			return apiReturn(2, '文件上传失败');
		}
	}
}

